package com.djhu.newscollector.crawel.imp.cl;


import com.djhu.newscollector.crawel.imp.cl.entity.Img;
import com.djhu.newscollector.crawel.imp.cl.entity.ImgRequest;
import com.djhu.newscollector.crawel.imp.cl.entity.ImgResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;

public class FileDownLoader {
    private static AtomicInteger atomicInteger = new AtomicInteger(1);

    private int retrytime = 3;

    public ImgResponse download(ImgRequest imgRequest) throws Exception {
        String title = imgRequest.getTitle();
        if (title.contains("?")){
            title = title.replaceAll("\\?","");
        }
        File dir = null;
        try {
            dir = new File(imgRequest.getDir()+ "/" + title);
            FileUtils.forceMkdir(dir);
        }catch (Exception e){
            dir = new File(imgRequest.getDir()+ "/" + atomicInteger.incrementAndGet());
            FileUtils.forceMkdir(dir);
        }
        //File dir = new File(imgRequest.getDir()+ "/" + title);
       // FileUtils.forceMkdir(dir);
        boolean success = false;
        AtomicInteger integer = new AtomicInteger(1);
        for (Img img:imgRequest.getImg()){
            String url = img.getImageurl();
            String name = img.getFilename();
            if (StringUtils.isEmpty(name)){
                name = createNameByUrl(url,integer);
                img.setFilename(dir.getAbsolutePath() + "/" + name);
            }
            success = Commons.downloadFile(img.getImageurl(),img.getFilename(),retrytime);
            img.setSuccess(success);
        }
        return new ImgResponse(imgRequest.getImg());
    }

    private String createNameByUrl(String url,AtomicInteger integer) {
        //int lastnIndex = url.lastIndexOf("/");
        //String name = url.substring(lastnIndex+1,url.length());
        //https://xxx.freeimage.us/image.php?id=D101_5A71A1B7&jpg
        int pos = integer.getAndIncrement();
        return pos + "." + "jpg";
    }

    public static void main(String[] args) {
        String url = "http://www.srimg.com/i/?i=u/20180210/0848595.jpg";
        FileDownLoader fileDownLoader = new FileDownLoader();
        System.out.println(fileDownLoader.createNameByUrl(url,new AtomicInteger(1)));
    }

}
